<template>
  <div>
    <form action="/">
      <van-search
        v-model="searchVal"
        show-action
        placeholder="请输入搜索关键词"
        @search="searchOnSearch"
        @cancel="searchOnCancel"
      />
    </form>
    <!-- 搜索列表 -->
    <van-swipe-cell :data-id="item.id" :before-close="searchBeforeClose" v-for="item in list" :key="item.id">
      <van-cell :border="true" :title="item.name" :value="item.ctime | dataFormat" />
      <template slot="right">
        <van-button square type="danger" text="删除" />
      </template>
    </van-swipe-cell>
    <!-- 搜索历史 -->
    <div v-show="isShow">
      <van-cell value="搜索历史" v-show="searchHistory">
          <i @click="removeSearch" class="deleteIcon" slot="right-icon" name="delete"><van-icon name="delete" /></i>
      </van-cell>
      <div class="searchTag">
        <van-tag v-for="(item, index) in searchList" :key="index">{{item}}</van-tag>
      <!-- 分割线 -->
      <van-divider v-show="searchEmpty">暂无搜索历史</van-divider>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Dialog } from 'vant'

export default {
  name: 'Search',
  data () {
    return {
      // 搜索框
      message: '',
      searchVal: '',
      finished: true,
      loading: false,
      list: [],
      // 历史记录
      searchList: [],
      searchHistory: true,
      searchEmpty: false,
      isShow: false
    }
  },

  created () {
    this.getSearch()
  },

  methods: {
    // 提交获取搜索数据
    async searchOnSearch (val) {
      this.isShow = false
      this.searchEmpty = false
      const { data: res } = await this.$axios.get('/api/getprodlist')
      if (this.searchVal.trim().length === 0) return
      if (res.status !== 0) return
      this.list = res.message
      // 提交数据 增加历史记录
      this.searchList.push(this.searchVal)
      // 去重
      var arr = this.searchList = [...new Set(this.searchList)]
      // 添加到本地存储
      var str = JSON.stringify(arr)
      window.localStorage.setItem('tempSearch', str)
      str = JSON.parse(str)
    },

    // 清除搜索记录
    removeSearch () {
      window.localStorage.clear('tempSearch')
      this.searchList = []
      this.searchEmpty = true
    },

    // 页面刷新获取搜素记录
    getSearch () {
      var str = window.localStorage.getItem('tempSearch')
      this.isShow = true
      if (str == null) {
        this.searchEmpty = true
        return
      }
      this.searchList = JSON.parse(str)
    },

    // 取消
    searchOnCancel () {
      this.list = []
      this.searchVal = ''
      this.isShow = true
    },

    // position 为关闭时点击的位置
    // instance 为对应的 SwipeCell 实例
    searchBeforeClose ({ position, instance }) {
      switch (position) {
        case 'left':
        case 'cell':
        case 'outside':
          break
        case 'right':
          Dialog.confirm({
            message: '确定删除吗？'
          }).then(async () => {
            const id = instance.$attrs
            // 根据id删除数据\
            const { data: res } = await this.$axios.get('api/delproduct/' + id['data-id'])
            if (res.status !== 0) return this.$toast('删除失败')
            this.$toast.success('删除成功')
            // 远程接口删除成功,本地数据也要更新
            this.searchOnSearch()
          })
          break
      }
    },

    // 跳转添加页面
    addgoods () {
      this.$router.push('/addgoods')
    },

    // 返回
    back () {
      this.$router.go(-1)
    }
  },

  components: {
  }
}

// 格式化时间    参数可以传默认值 df=' - '  default=' : '
Vue.filter('dataFormat', val => {
  const dt = new Date(val)
  const y = dt.getFullYear()
  const m = (dt.getMonth() + '' + 1).padStart(2, 0)
  const d = (dt.getDate() + '').padStart(2, 0)
  // const h = (dt.getHours() + '').padStart(2, 0)
  // const mm = (dt.getMinutes() + '').padStart(2, 0)
  // const s = (dt.getSeconds() + '').padStart(2, 0)
  // return `${y}-${m}-${d}  ${h}-${mm}-${s}`
  return `商品上架时间: ${y}-${m}-${d}`
})

</script>
<style scoped >
/* 删除icon */
.deleteIcon {
  margin-top: 3px;
  font-size: 12px;
}

.van-divider {
  margin-top: 20px;
  border-color: #ccc;
  padding: 0px 10px;
  color: #333;
}

.searchTag {
  padding: 0px 10px;
  /* margin-top: -5px; */
  background-color: #fff;
}

.van-tag {
  margin: 3px 5px;
}

/* < icon下移 */
.van-icon {
  top: 3px;
}

</style>
